#include "mainwindow.h"
#include "./ui_mainwindow.h"

#include <QGuiApplication>
#include <QClipboard>
#include <QMimeData>
#include <QMessageBox>
#include <QButtonGroup>
#include <QDebug>

#include "utils.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    ui->checkBoxAutoConvert->setCheckState(Qt::Checked);
    ui->btnConvert->setEnabled(false);
    this->setWindowTitle(QString("%1 v%2").arg(qApp->applicationName(), qApp->applicationVersion()));

    QButtonGroup* btnGroup = new QButtonGroup(this);
    btnGroup->addButton(ui->rdBtnHex2Utf8);
    btnGroup->addButton(ui->rdBtnUtf82Hex);

    connect(btnGroup, &QButtonGroup::buttonClicked,  this, [this](QAbstractButton* btn){
        if (btn == ui->rdBtnHex2Utf8) {
            input_type_ = InputType::Hex;
            ui->labelInput->setText("Hex");
            ui->labelOutput->setText("Utf8");
        } else {
            input_type_ = InputType::Utf8;
            ui->labelInput->setText("Utf8");
            ui->labelOutput->setText("Hex");
        }

        doConvert();
    });

    ui->rdBtnHex2Utf8->setChecked(Qt::Checked);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::doConvert()
{
    const QString input = ui->textEditInput->toPlainText();
    if (input_type_ == InputType::Hex) {
        const QPair<bool, QString> convertRes = Utils::hexToUtf8(input);
        ui->textEditOutput->setPlainText(convertRes.second);
        ui->statusBar->showMessage(QString("转换%1!").arg(convertRes.first ? "成功" : "失败"));
    } else {
        QString convertRes = Utils::utf8ToHex(input);
        ui->textEditOutput->setPlainText(convertRes);
        ui->statusBar->clearMessage();
    }
}

void MainWindow::on_checkBoxAutoConvert_stateChanged(int arg1)
{
    if (arg1 == Qt::Checked) {
        auto_convert_ = true;
    } else {
        auto_convert_ = false;
    }
    ui->btnConvert->setEnabled(!auto_convert_);
}


void MainWindow::on_btnPaste_clicked()
{
    const QClipboard* clipBoard = QGuiApplication::clipboard();
    const QMimeData *mimeData = clipBoard->mimeData();
    if (mimeData->hasText()) {
        ui->textEditInput->setPlainText(mimeData->text());
    } else {
        QMessageBox::information(this, "提示", "一键粘贴失败，剪切板中无可粘贴文本！");
    }
}

void MainWindow::on_btnConvert_clicked()
{
    doConvert();
}

void MainWindow::on_btnCopy_clicked()
{
    const QString text = ui->textEditOutput->toPlainText();
    QClipboard* clipBoard = QGuiApplication::clipboard();
    clipBoard->setText(text);
}


void MainWindow::on_textEditInput_textChanged()
{
    if (auto_convert_) {
        doConvert();
    }
}

